package com.beiji.usercentert.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.beiji.usercentert.comoon.BaseResponse;
import com.beiji.usercentert.comoon.ErrorCode;
import com.beiji.usercentert.constant.UserConstant;
import com.beiji.usercentert.exception.BusinessException;
import com.beiji.usercentert.model.domain.User;
import com.beiji.usercentert.model.dto.UserLoginDTO;
import com.beiji.usercentert.model.dto.UserRegisterDTO;
import com.beiji.usercentert.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户接口
 *
 * @author beiji
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    /**
     * 用户注册
     *
     * @param userRegisterDTO
     * @return 用户id
     */
    @PostMapping("/register")
    public Long userRegister(@RequestBody UserRegisterDTO userRegisterDTO) {
        log.info("用户注册");
        //校验
        if (ObjectUtils.isEmpty(userRegisterDTO)) {
            return null;
        }

        String userAccount = userRegisterDTO.getUserAccount();
        String userPassword = userRegisterDTO.getUserPassword();
        String checkPassword = userRegisterDTO.getCheckPassword();
        String planetCode = userRegisterDTO.getPlanetCode();

        long userId = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return userId;
    }

    /**
     * 用户登录
     *
     * @param userLoginDTO
     * @param request
     * @return 用户
     */
    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginDTO userLoginDTO, HttpServletRequest request) {
        log.info("用户登录");
        //校验
        if (ObjectUtils.isEmpty(userLoginDTO)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.doLogin(userLoginDTO.getUserAccount(), userLoginDTO.getUserPassword(), request);
        return BaseResponse.success(user);
    }

    /**
     * 用户查询
     *
     * @param username 用户名
     * @return 脱敏用户信息
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> SearchUsers(String username, HttpServletRequest request) {
        log.info("用户查询");
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_AUTH);
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNoneBlank(username)) {
            queryWrapper.eq(User::getUsername, username);
        }


        List<User> userList = userService.list(queryWrapper)
                .stream()
                .map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());

        return BaseResponse.success(userList);
    }

    /**
     * 用户注销
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        Integer integer = userService.userLogout(request);
        return BaseResponse.success(integer);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request) {
        log.info("删除用户id");
        if (!isAdmin(request)) {
            throw new BusinessException(ErrorCode.NOT_AUTH);
        }

        if (id < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = userService.removeById(id);
        return BaseResponse.success(b);
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        //检验登录态是否有信息
        User userCurrent = (User) userObj;
        if (ObjectUtils.isEmpty(userCurrent)) {
            return null;
        }

        //更新登录态
        Long userCurrentId = userCurrent.getId();
        //返回脱敏之后的用户信息
        User safetyUser = userService.getSafetyUser(userService.getById(userCurrentId));
        return BaseResponse.success(safetyUser);

    }

    //身份校验
    public boolean isAdmin(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user == null || user.getUserRole() != 1) {
            return false;
        }
        return true;
    }
}
